//
//  ViewController.swift
//  UI04-TableView
//
//  Created by yao_yu on 14-8-22.
//  Copyright (c) 2014年 yao_yu. All rights reserved.
//
//  表格视图代理, 表格数据源代理, 提示对话框代理

import UIKit

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource, UIAlertViewDelegate {
    
    var tableView = UITableView()
    var contactGroups = [KCContactGroup]()
    var selectedIndexPath = NSIndexPath()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        
        setupViews()
        initData()
    }
    
    func setupViews(){
        view.backgroundColor = UIColor.blackColor()
        tableView = UITableView(frame: view.bounds, style: UITableViewStyle.Grouped)
        tableView.dataSource = self
        tableView.delegate = self
        tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
        view.addSubview(tableView)
        let views = ["tableView":tableView]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|[tableView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-20-[tableView]-|", options: NSLayoutFormatOptions(0), metrics: nil, views: views))
    }
    
    func initData(){
        contactGroups = [KCContactGroup]()
        var contacts = [KCContact]()
        contacts.append(KCContact(firstName: "张", lastName: "三丰", phoneNumber: "13012345678"))
        contacts.append(KCContact(firstName: "张", lastName: "荣光", phoneNumber: "13178080929"))
        contacts.append(KCContact(firstName: "张", lastName: "磊", phoneNumber: "13260778906"))
        contactGroups.append(KCContactGroup(name: "z", detail: "以z开头", contacts: contacts))
        contacts = [KCContact]()
        contacts.append(KCContact(firstName: "李", lastName: "信", phoneNumber: "13312345678"))
        contacts.append(KCContact(firstName: "李", lastName: "四", phoneNumber: "13478080929"))
        contacts.append(KCContact(firstName: "李", lastName: "大宝", phoneNumber: "13660778906"))
        contactGroups.append(KCContactGroup(name: "l", detail: "以L开头", contacts: contacts))
        contacts = [KCContact]()
        contacts.append(KCContact(firstName: "孙", lastName: "子", phoneNumber: "13612345678"))
        contacts.append(KCContact(firstName: "孙", lastName: "中山", phoneNumber: "13778080929"))
        contacts.append(KCContact(firstName: "孙", lastName: "鑫", phoneNumber: "13860778906"))
        contactGroups.append(KCContactGroup(name: "s", detail: "以s开头", contacts: contacts))
        contacts = [KCContact]()
        contacts.append(KCContact(firstName: "王", lastName: "敏", phoneNumber: "13612345678"))
        contacts.append(KCContact(firstName: "王", lastName: "大锤", phoneNumber: "13778080929"))
        contacts.append(KCContact(firstName: "王", lastName: "五", phoneNumber: "13860778906"))
        contacts.append(KCContact(firstName: "王", lastName: "钦燕", phoneNumber: "13860778906"))
        contacts.append(KCContact(firstName: "王", lastName: "明昊", phoneNumber: "13860778906"))
        contacts.append(KCContact(firstName: "王", lastName: "家庆", phoneNumber: "13860778906"))
        contacts.append(KCContact(firstName: "王", lastName: "治国", phoneNumber: "13860778906"))
        contacts.append(KCContact(firstName: "王", lastName: "晓泽", phoneNumber: "13860778906"))
        contacts.append(KCContact(firstName: "王", lastName: "莹莹", phoneNumber: "13860778906"))
        contacts.append(KCContact(firstName: "王", lastName: "萱萱", phoneNumber: "13860778906"))
        contactGroups.append(KCContactGroup(name: "w", detail: "以w开头", contacts: contacts))
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //#pragma mark - 数据源方法
    // 分组数
    func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
        return contactGroups.count
    }
    
    // 每组行数
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
        return contactGroups[section].contacts.count
    }
    
    // 单元格
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
        let group = contactGroups[indexPath.section]
        let contact = group.contacts[indexPath.row]
        let cellIdentifier = "MyCell"
        let cellIdentifierFirstRow = "FirstRow"
        let identifier = indexPath.row == 0 ? cellIdentifierFirstRow : cellIdentifier
        var _cell: AnyObject! = tableView.dequeueReusableCellWithIdentifier(identifier)
        if _cell == nil{
            _cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: identifier)
            if indexPath.row == 0{
                let sw = UISwitch()
                sw.addTarget(self, action: "switchValueChange:", forControlEvents: UIControlEvents.ValueChanged)
                (_cell as UITableViewCell).accessoryView = sw
            } else {
                (_cell as UITableViewCell).accessoryType = UITableViewCellAccessoryType.DetailButton
            }
        }
        let cell = _cell! as UITableViewCell
        
        if indexPath.row == 0{
//            (cell.accessoryView as UISwitch).tag = indexPath.section
            cell.accessoryView.tag = indexPath.section
        }
        
        cell.textLabel.text = contact.name
        cell.detailTextLabel.text = contact.phoneNumber
        
        return cell
    }
    
    // 分组头标题
    func tableView(tableView: UITableView!, titleForHeaderInSection section: Int) -> String! {
        return contactGroups[section].name
    }
    
    // 分组尾部名称
    func tableView(tableView: UITableView!, titleForFooterInSection section: Int) -> String! {
        return contactGroups[section].detail
    }
    
    // 设置索引
    func sectionIndexTitlesForTableView(tableView: UITableView!) -> [AnyObject]! {
        var groups = [AnyObject]()
        for group in contactGroups{
            groups.append(group.name as NSString)
        }
        return groups
    }
    
    // 设置高度
    func tableView(tableView: UITableView!, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0{
            return 50
        }
        return 40
    }
    
    //    func tableView(tableView: UITableView!, heightForFooterInSection section: Int) -> CGFloat {
    //        return 40
    //    }
    //
    //    func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
    //        return 60
    //    }
    
    //点击行
    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
        selectedIndexPath = indexPath
        let group = contactGroups[indexPath.section]
        let contact = group.contacts[indexPath.row]
        
        let alert = UIAlertView(title: "修改\(contact.name)电话", message: contact.phoneNumber, delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定")
        alert.alertViewStyle = UIAlertViewStyle.PlainTextInput
        let textField = alert.textFieldAtIndex(0)
        textField.text = contact.phoneNumber
        alert.show()
    }
    
    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
        if buttonIndex == 1{
            let textField = alertView.textFieldAtIndex(0)
            let group = contactGroups[selectedIndexPath.section]
            let contact = group.contacts[selectedIndexPath.row]
            contact.phoneNumber = textField.text
            tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: UITableViewRowAnimation.Left)
        }
    }
    
    override func preferredStatusBarStyle() -> UIStatusBarStyle {
        return UIStatusBarStyle.LightContent
    }
    
    func switchValueChange(sw:UISwitch){
        println("section:\(sw.tag), switch:\(sw.on)")
    }
}

